#include "VisioCommon.h"
#include "texture.h"


Texture::Texture(GLenum TextureTarget, const std::string& FileName)
{
    m_textureTarget = TextureTarget;
    m_fileName      = FileName;
    m_Image         = NULL;
	m_bLoaded		= false;
}

Texture::Texture(GLenum	TextureTarget, const cv::Mat Image)
{
	m_textureTarget = TextureTarget;
	m_fileName = "";
	m_Image = Image;
	m_bLoaded = true;
}

bool Texture::Load()
{
	if (!m_bLoaded)
	{
		//Texture not yet loaded
		IplImage* img1;
		img1 = cvLoadImage( m_fileName.c_str(), 1 );
		m_Image = cv::Mat(img1);
	}

    if (m_Image.data == NULL)
	{
		// could not load image
        CONSOLE("Error loading texture %s\n", m_fileName.c_str());
        return false;
    }

    glGenTextures(1, &m_textureObj);
    glBindTexture(m_textureTarget, m_textureObj);
    glTexImage2D(m_textureTarget, 0, GL_RGB, m_Image.cols, m_Image.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, m_Image.data);
    glTexParameterf(m_textureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameterf(m_textureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    return true;
}

void Texture::Bind(GLenum TextureUnit) const
{
    glActiveTexture(TextureUnit);
    glBindTexture(m_textureTarget, m_textureObj);
}
